package de.velvettear.bruteforce.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.math.BigDecimal;
import java.math.RoundingMode;

import javax.swing.JProgressBar;

public class FileHelper {

	public static File copy(File source) {
		return copy(null, source, null, true);
	}
	
	public static File copy(File source, boolean overwrite) {
		return copy(null, source, null, overwrite);
	}
	
	public static File copy(File source, File destination, boolean overwrite) {
		return copy(null, source, destination, overwrite);
	}
	
	public static File copy(JProgressBar progressbar, File source, File destination, boolean overwrite) {
		File copy = null;
				
		try {
			if (source.exists()) {
				FileInputStream in = new FileInputStream(source);
				
				if (destination == null) {
					String path = source.getAbsolutePath().substring(0, source.getAbsolutePath().lastIndexOf(File.separator));
					String name = source.getName().substring(0, source.getName().lastIndexOf("."));
					String extension = source.getName().substring(source.getName().lastIndexOf("."), source.getName().length());
					destination = new File(path + File.separator + Timestamp.getUnformatted() + " " + name + extension);
				}
				
				if (destination.exists()) {
					if (overwrite) {
						destination.delete();
					} else {
						return copy;
					}
				}
				
				FileOutputStream out = new FileOutputStream(destination);
				
				long fileSize = source.length();
				long counter = 0;
				int tmp = 0;
				
				byte[] buffer = new byte[1024];
								
				while((tmp = in.read(buffer)) != -1) {
					counter += tmp;
								
					if (progressbar != null) {
						BigDecimal percentage = (new BigDecimal(counter).divide(new BigDecimal(fileSize), 4, RoundingMode.HALF_UP)).multiply(new BigDecimal(String.valueOf(100)));				
						progressbar.setValue(percentage.intValue());
					}					
					
					out.write(buffer, 0, tmp);
				}
			}
			
			copy = destination;
		} catch (Exception e) {
			Log.error(e);
		}		
		
		return copy;
	}
	
	public static File copyToTemporaryThreadDirectory(String threadName, File source) {
		return copyToTemporaryThreadDirectory(threadName, source, true);
	}
	
	public static File copyToTemporaryThreadDirectory(String threadName, File source, boolean overwrite) {
		File copy = null;
		if (source.exists()) {
			File directory = DirectoryHelper.createTemporaryThreadDirectory(threadName);
			
			if (directory.exists() && directory.isDirectory()) {
				copy = FileHelper.copy(source, new File(directory.getAbsolutePath() + File.separator + source.getName()), overwrite);
			}
		}
		return copy;
	}
	
}
